from flask import Flask, render_template
from web.setting import ConfigSettings, components_init
from web.view import register_blueprints


def create_app() -> Flask:
    """
    创建app
    :return: app
    """
    app = Flask(__name__)
    app.config.from_object(ConfigSettings)
    register_blueprints(app)
    components_init(app)

    @app.cli.command("init_sql")
    def init_sql():
        """
        初始化数据库
        """
        from web.models import db, User
        try:
            db.create_all()
            if User.query.filter_by(username='admin').first():
                print('数据库已存在')
                return
            user = User()
            user.username = 'admin'
            user.password = 'admin'
            user.authority = 2
            user.authority_name = '管理员'
            user.save()
            print('初始化数据库成功，用户名：admin，密码：admin')
            print('请登录后修改密码')
        except Exception as e:
            print(e)

    @app.cli.command("drop_sql")
    def drop_sql():
        """
        删除所有数据表
        """
        from web.models import db
        try:
            db.drop_all()
            print('删除数据表成功')
        except Exception as e:
            print(e)

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html')

    return app
